import React from 'react';
import {connect} from 'react-redux'
import {BackHandler, View,Alert} from 'react-native';
import AppNavigator from './appNavigator'
import LoginNavigator from './loginNavigator'
import {addNavigationHelpers, NavigationActions} from 'react-navigation';

import {
    createReduxBoundAddListener,
} from 'react-navigation-redux-helpers';

import {getConfig, configkey} from '../utils/NativeUtil';

import {gotoView} from './actions';

const addListener = createReduxBoundAddListener("root");

class App extends React.Component {
    componentDidMount() {
        const self = this;
        let keys = `${configkey.UserToken}`;
        getConfig(keys, (values) => {
            let token = values[configkey.UserToken];
            if (token == undefined || token == "") {
                self.props.dispatch(gotoView("login"))
            } else {
                self.props.dispatch(gotoView("home"))
            }
        })
        BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
    }

    componentWillUnmount() {
        BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
    }

    onBackPress = () => {
        const {dispatch, nav} = this.props;
        if (nav.index === 0) {
            return false;
        }
     
        dispatch(NavigationActions.back());
        return true;
    };

    render() {
        if (this.props.homeView == "login") {
            return <LoginNavigator navigation={{
                dispatch: this.props.dispatch,
                state: this.props.nav,
                addListener
            }}/>
        } else if (this.props.homeView == "home") {
            return <AppNavigator navigation={{
                dispatch: this.props.dispatch,
                state: this.props.nav,
                addListener
            }}/>
        } else {
            return <View></View>
        }
    }
}

const mapStateToProps = (state) => ({
    nav: state.nav,
    homeView: state.app.homeView
});

const AppWithNavigationState = connect(mapStateToProps)(App);

export default AppWithNavigationState;